package com.qf.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;

@Service
public class UploadFileService {
    @Value("${blog.qiniu.ak}")
    private String accessKey;

    @Value("${blog.qiniu.sk}")
    private String secretKey;

    @Value("${blog.qiniu.bucket}")
    private String bucket;

    @Autowired
    private UploadManager uploadManager;

    @Value("${blog.qiniu.host}")
    private String host;

    /**
     * 把文件上传到七牛云OSS，返回文件的地址
     * @param ips 文件流
     * @param size 文件大小
     * @param key 文件名称
     * @return 文件的绝对路径
     */
    public String uploadFile(InputStream ips, Long size, String key) {
        Auth auth = Auth.create(accessKey, secretKey);
        // 1、获取一个上传的token
        String upToken = auth.uploadToken(bucket);
        try {
//             2、开始上传文件
            Response response = uploadManager.put(ips, size, key, upToken, null, null, false);

//            3、解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return host + putRet.key;
        } catch (QiniuException ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
